﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Sdari.Api.DbModel;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace Sdari.Api.Gateway.Controllers
{
    [Authorize]
    public class ConsumerInfoController : Controller
    {
        private readonly ITokenServiceContext _db;
        private readonly ILogger<ConsumerInfoController> _logger;

        public ConsumerInfoController(ITokenServiceContext context, ILogger<ConsumerInfoController> logger)
        {
            _db = context;
            _logger = logger;
        }

        // GET: ConsumerInfoes
        public async Task<IActionResult> Index()
        {
            return View(await _db.ConsumerInfo.ToListAsync());
        }

        // GET: ConsumerInfoes/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var consumerInfo = await _db.ConsumerInfo
                .FirstOrDefaultAsync(m => m.Id == id);
            if (consumerInfo == null)
            {
                return NotFound();
            }

            return View(consumerInfo);
        }

        // GET: ConsumerInfoes/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: ConsumerInfoes/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Name,ClientId,Secret,Ipv6,Description")] ConsumerInfo consumerInfo)
        {
            if (ModelState.IsValid)
            {
                consumerInfo.Uid = Guid.NewGuid();
                if (IPAddress.TryParse($"{Request.Form["Ipv4[0]"]}.{Request.Form["Ipv4[1]"]}.{Request.Form["Ipv4[2]"]}.{Request.Form["Ipv4[3]"]}", out var ipv4))
                    consumerInfo.Ipv4 = ipv4.GetAddressBytes();
                consumerInfo.CreateDate = DateTime.Now;
                consumerInfo.Creator = User.FindFirst("work_no")?.Value;
                _db.Add(consumerInfo);
                await _db.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(consumerInfo);
        }

        // GET: ConsumerInfoes/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var consumerInfo = await _db.ConsumerInfo.FindAsync(id);
            if (consumerInfo == null)
            {
                return NotFound();
            }
            return View(consumerInfo);
        }

        // POST: ConsumerInfoes/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Uid,Id,Name,ClientId,Secret,Ipv4,Ipv6,Description")] ConsumerInfo consumerInfo)
        {
            if (id != consumerInfo.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _db.Attach(consumerInfo);
                    var en = _db.Entry(consumerInfo);
                    en.Property(nameof(consumerInfo.Name)).IsModified = true;
                    en.Property(nameof(consumerInfo.ClientId)).IsModified = true;
                    en.Property(nameof(consumerInfo.Secret)).IsModified = true;
                    if(IPAddress.TryParse($"{Request.Form["Ipv4[0]"]}.{Request.Form["Ipv4[1]"]}.{Request.Form["Ipv4[2]"]}.{Request.Form["Ipv4[3]"]}", out var ipv4))
                    {
                        en.Entity.Ipv4 = ipv4.GetAddressBytes();
                        en.Property(nameof(consumerInfo.Ipv4)).IsModified = true;
                    }
                    en.Property(nameof(consumerInfo.Ipv6)).IsModified = true;
                    en.Property(nameof(consumerInfo.Description)).IsModified = true;
                    consumerInfo.LastUpdatedDate = DateTime.Now;
                    consumerInfo.LastUpdater = User.FindFirst("work_no")?.Value;
                    //_context.Update(consumerInfo);
                    await _db.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ConsumerInfoExists(consumerInfo.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(consumerInfo);
        }

        // GET: ConsumerInfoes/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var consumerInfo = await _db.ConsumerInfo
                .FirstOrDefaultAsync(m => m.Id == id);
            if (consumerInfo == null)
            {
                return NotFound();
            }

            return View(consumerInfo);
        }

        // POST: ConsumerInfoes/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var consumerInfo = await _db.ConsumerInfo.FindAsync(id);
            _db.ConsumerInfo.Remove(consumerInfo);
            await _db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool ConsumerInfoExists(int id)
        {
            return _db.ConsumerInfo.Any(e => e.Id == id);
        }
    }
}
